package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Description: 全局异常处理器 底层实现shi代理？？？
 * @Title: GlobalExceptionHandler
 * @Package com.itheima.riggie.common
 * @Author: 🐟
 * @Copyright 🐟
 * @CreateTime: 2022/9/8 16:50
 */
@ResponseBody
@Slf4j
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
    /**
     * @param
     * @return null
     * @Description: sql异常处理器
     * @Author 977254129@qq.com
     * @CreateTime 2022/9/8 16:57
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.info(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] s = e.getMessage().split(" ");
            return R.error(s[2] + "已经存在，请不要重复添加");
        }
        return R.error("操作失败了，未知错误");

    }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
